package com.xiaolin.ssosystem.controller;

import com.google.common.util.concurrent.RateLimiter;
import com.xiaolin.ssosystem.model.dto.LogoutDto;
import com.xiaolin.ssosystem.model.dto.UserDto;
import com.xiaolin.ssosystem.model.dto.UserInfoFetch;
import com.xiaolin.ssosystem.service.SSOService;
import com.xiaolin.ssosystem.utils.OptResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaolin
 * @description 描述
 * @since 2024/7/18
 */
@Slf4j
@RestController
@RequestMapping("/ssoAuth")
public class SSOController {

    @Autowired
    private SSOService ssoService;

    @Autowired
    private RateLimiter rateLimiter;

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    public OptResult login(@RequestBody UserDto userDto, HttpServletResponse response) {
        if (rateLimiter.tryAcquire()) {
            return ssoService.login(userDto, response);
        } else {
            log.warn("系统繁忙，请稍后重试。");
            return new OptResult(400, null);
        }
    }

    /**
     * 获取令牌
     *
     * @return
     */
    @PostMapping("/getCode")
    public OptResult getCode(HttpServletRequest request) {
        if (rateLimiter.tryAcquire()) {
            return ssoService.getCode(request);
        } else {
            log.warn("系统繁忙，请稍后重试。");
            return new OptResult(400, null);
        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @PostMapping("/info")
    public OptResult info(@RequestBody UserInfoFetch userInfoFetch, HttpServletRequest request) {
        return ssoService.info(userInfoFetch, request);
    }

    /**
     * 注销
     *
     * @return
     */
    @PostMapping("/logout")
    public OptResult logout(@RequestBody LogoutDto logoutDto) {
        return ssoService.logout(logoutDto);
    }
}
